import React, { useState, useEffect, useContext } from 'react';
import { Row, Col, Table, message, Tag } from 'antd';
import axios from 'axios';
import LittleHeader from '../../components/LittleHeader';
import CreateBugs from '../../components/CreateBugs';
import withAuth from '../../components/WithAuth';
import MainLayout from '../../components/MainLayout';
import { AuthContext } from '../../contexts/AuthContext';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

const PersonalBugs = () => {
    const [allData, setAllData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 15,
        total: 0,
    });
    const { t } = useTranslation();
    const { token } = useContext(AuthContext);
    const [refreshKey, setRefreshKey] = useState(0);
    const [showSuccessMessage, setShowSuccessMessage] = useState(true);
    const navigate = useNavigate();

    const getSeverityLevel = (rank) => {
        switch (rank) {
            case 5:
                return t('严重');
            case 4:
                return t('高危');
            case 3:
                return t('中危');
            case 2:
                return t('低危');
            case 1:
                return t('可忽略');
            default:
                return t('未知');
        }
    };

    const columns = [
        {
            title: t('漏洞ID'),
            dataIndex: 'id',
            key: 'id',
            width: 150,
            fixed: 'left',
            render: (text) => <a>{text}</a>,
        },
        {
            title: t('提供者'),
            dataIndex: 'assigner',
            key: 'assigner',
            width: 200,
            render: (assigners) => (
                <div>
                    {assigners?.map((email, index) => (
                        <Tag color="blue" key={index}>{email}</Tag>
                    ))}
                </div>
            ),
        },
        {
            title: t('严重程度'),
            key: 'severity',
            width: 120,
            render: (_, record) => {
                const severity = getSeverityLevel(record.severities?.[0]?.rank);
                let color = '';
                switch (severity) {
                    case t('严重'):
                        color = '#cf1322';
                        break;
                    case t('高危'):
                        color = '#d4380d';
                        break;
                    case t('中危'):
                        color = '#d46b08';
                        break;
                    case t('低危'):
                        color = '#389e0d';
                        break;
                    case t('可忽略'):
                        color = '#d9d9d9';
                        break;
                    default:
                        color = '#d9d9d9';
                }
                return <span style={{ color, fontWeight: 'bold' }}>{severity}</span>;
            },
            sorter: (a, b) => {
                const severityOrder = {
                    [t('严重')]: 5,
                    [t('高危')]: 4,
                    [t('中危')]: 3,
                    [t('低危')]: 2,
                    [t('可忽略')]: 1,
                    [t('未知')]: 0
                };
                return severityOrder[getSeverityLevel(a.severities?.[0]?.rank)] -
                    severityOrder[getSeverityLevel(b.severities?.[0]?.rank)];
            },
        },
        {
            title: t('评测'),
            key: 'cvss',
            width: 250,
            render: (_, record) => (
                <div>
                    {record.severities?.map((severity, index) => (
                        <div key={index} style={{ marginBottom: 8 }}>
                            <div><strong>{t('严重程度方案')}:</strong> {severity.scheme}</div>
                            <div><strong>{t('严重程度版本')}:</strong> {severity.value?.version}</div>
                            <div><strong>{t('严重程度向量')}:</strong> {severity.value?.vector}</div>
                            <div><strong>{t('严重程度来源')}:</strong> {severity.source}</div>
                        </div>
                    ))}
                </div>
            ),
        },
        {
            title: t('描述'),
            dataIndex: 'description',
            key: 'description',
            width: 300,
            render: (text) => <div style={{ whiteSpace: 'pre-line' }}>{text}</div>,
        },
    ];

    const fetchAllData = async () => {
        console.log('fetchAllData 被调用'); // 添加日志调试
        setLoading(true);
        try {
            const response = await axios.post('/api/v1/vulnerability/queryByUser', {
                page: 1,
                size: 10000
            }, {
                headers: {
                    Authorization: token,
                }
            });

            if (response.data?.code === 0) {
                const rawData = response.data.data || [];
                setAllData(rawData);
                setPagination(prev => ({
                    ...prev,
                    total: rawData.length
                }));
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'));
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            } else {
                setAllData([]);
            }
        } catch (error) {
            console.error(t('获取数据失败:'), error);
            message.error(t('失败'));
            setAllData([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (token) {
            setShowSuccessMessage(true);
            console.log('useEffect 触发，token:', token, 'refreshKey:', refreshKey); // 添加日志调试
            fetchAllData();
        }
    }, [token, refreshKey]);

    const handleCreateSuccess = () => {
        setShowSuccessMessage(false);
        fetchAllData();
    };

    const handleRefresh = () => {
        setRefreshKey(prev => prev + 1);
    };

    const getCurrentPageData = () => {
        const { current, pageSize } = pagination;
        const start = (current - 1) * pageSize;
        const end = start + pageSize;
        return allData.slice(start, end);
    };

    const handleTableChange = (newPagination) => {
        setPagination(newPagination);
    };

    return (
        <MainLayout defaultSelectedKey="5">
            <LittleHeader />
            <div>
                <CreateBugs onCreateSuccess={handleCreateSuccess} />
                <Row gutter={20} style={{ marginTop: 20 }}>
                    <Col span={24}>
                        <Table
                            columns={columns}
                            dataSource={getCurrentPageData()}
                            rowKey="id"
                            loading={loading}
                            pagination={{
                                ...pagination,
                                showSizeChanger: true,
                                pageSizeOptions: ['15', '30', '50', '100'].map(num => t(num)),
                                showTotal: (total) => t('共 {{total}} 条数据', { total }),
                            }}
                            onChange={handleTableChange}
                            scroll={{ x: 1500 }}
                            bordered
                            size="middle"
                        />
                    </Col>
                </Row>
            </div>
        </MainLayout>
    );
};

export default withAuth(PersonalBugs);    